package com.jinlejia.erp.ui.house.prospect;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.prospect.UploadImageGridViewAdapter;
import com.jinlejia.erp.databinding.ActivityProspectSubdividedBinding;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.jinlejia.erp.utils.ViewHolderUtil;
import com.weight.CustomToast;

import java.util.ArrayList;
import java.util.List;

/**
 * 分间信息
 */
public class ProspectSubdividedActivity extends AppCompatActivity {

    public static final String PARAM_SOURCE = "PARAM_SOURCE";
    public static final String PARAM_ALL_SOURCE = "PARAM_ALL_SOURCE";

    //房屋名称
    private SubdividedGridAdapter houseNameAdapter;
    //朝向
    private SubdividedGridAdapter orientationAdapter;

    //窗户种类
    private SubdividedGridAdapter windowsAdapter;
    private UploadImageGridViewAdapter.Source cacheSource;
    private ArrayList<UploadImageGridViewAdapter.Source> cacheAllSources;
    private Helper helper;

    private innerOnGlobalLayoutListener innerOnGlobalLayoutListener;
    private ActivityProspectSubdividedBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_prospect_subdivided);
        binding.cancelButton.setOnClickListener(this::finish);
        binding.saveButton.setOnClickListener(this::finish);
        binding.toolbarBackImageView.setOnClickListener(v->finishActivity());

        binding.toolbarTitleTextView.setText("分间信息");
        helper = Helper.init(this);
        Bundle extras = getIntent().getExtras();
        if (extras!=null){
            cacheSource = extras.getParcelable(PARAM_SOURCE);
            cacheAllSources = extras.getParcelableArrayList(PARAM_ALL_SOURCE);
        }
        Intent intent = getIntent();
        String label = intent.getStringExtra(Type.PARAM.SUBDIVIDED_LABEL);
        int count = intent.getIntExtra(Type.PARAM.SUBDIVIDED_COUNT, 1);
        final int pageType = intent.getIntExtra(Type.PARAM.PAGE_TYPE, 0); //1新增 2修改 3补充
        initHouseNameGridView(count!=0,label,count);
        initAcreageLayout(true);
        final String rsCode = intent.getStringExtra(Type.PARAM.HOUSE_SOURCE_CODE);
        //region 设置字符过滤
        binding.acreageEditTextView.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if(source.equals(".") && dest.toString().length() == 0){
                    return "0.";
                }
                if(dest.toString().contains(".")){
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if(length == 3){
                        return "";
                    }
                }
                return null;
            }
        }});
        //endregion

        //region 设置键盘监听
        innerOnGlobalLayoutListener = new innerOnGlobalLayoutListener();
        binding.scrollView.getViewTreeObserver().addOnGlobalLayoutListener(innerOnGlobalLayoutListener);
        //endregion

        helper.http().getCompartmentInfoDictionary(new Helper.Http.CompartmentInfoDictionaryCallBack() {
            @Override
            public void onWindowsResult(List<String> windows) {
                if (windows==null){
                    initWindowsGridView(false,null);
                }else {
                    initWindowsGridView(true,windows);
                }
            }

            @Override
            public void onFacesResult(List<String> faces) {
                if (faces == null){
                    initOrientationGridView(false,null);
                }else {
                    initOrientationGridView(true,faces);
                }
            }

            @Override
            public void onOver() {
                //region 优先展示缓存的数据
                updateWindowsGridView(cacheSource.getWindows());
                updateOrientationGridView(cacheSource.getOrientation());
                updateHouseNameGridView(cacheSource.getHouseName());
                if (!TextUtils.isEmpty(cacheSource.getAcreage())){
                    updateAcreageLayout(cacheSource.getAcreage());
                }
                //endregion
                if (pageType!=2)return; //如果不是修改则，不查询数据进行填充
                String houseName = cacheSource.getHouseName();
                helper.http().listRoomDivision(rsCode, houseName,new Helper.Http.ListRoomDivisionCallBack() {
                    @Override
                    public void onWindowsResult(String windows) {
                        updateWindowsGridView(windows);
                    }

                    @Override
                    public void onFacesResult(String faces) {
                        updateOrientationGridView(faces);
                    }

                    @Override
                    public void onNameResult(String name) {
                        updateHouseNameGridView(name);
                    }

                    @Override
                    public void onSquareResult(String square) {
                        updateAcreageLayout(square);
                    }
                });
            }
        });
    }


    private class innerOnGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
        private int bottom1 = Integer.MIN_VALUE; //整个布局的高度

        @Override
        public void onGlobalLayout() {
            Rect rect = new Rect();
            //DecorView即为activity的顶级view
            getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
            if (bottom1==Integer.MIN_VALUE && binding.buttonsLayout.getVisibility()==View.VISIBLE){
                bottom1 = rect.bottom;
                return;
            }
            if (rect.bottom == bottom1){ //键盘关闭
                binding.buttonsLayout.setVisibility(View.VISIBLE);
            }else { //键盘弹出
                binding.buttonsLayout.setVisibility(View.GONE);
            }
        }
    }

    private CommonDialog mDialog;
    private void showDialog(String name, final CommonDialog.OnConfirmListener listener){
        if (mDialog == null){
            String content="[%s]已经存在，是否替换？";
            content = String.format(content,name);
            mDialog = new CommonDialog(this,"提示",content,"确认","取消");
            mDialog.setConfirmListener(new CommonDialog.OnConfirmListener() {
                @Override
                public void confirm() {
                    listener.confirm();
                    mDialog = null;
                }
            });
        }
        mDialog.show();
    }
    public void finish(View view) {

        switch (view.getId()) {
            case R.id.cancelButton:
                setResult(RESULT_CANCELED);
                break;
            case R.id.saveButton:
                if (!check())return; //表单输入检查
                GridSource houseSource = houseNameAdapter==null?null:houseNameAdapter.getSelectValue();
                String houseName = houseSource==null?null:houseSource.getText(); //房间名称
                String houseCacheName = houseSource==null?null:houseSource.getCacheText(); //房间名称-简称
                String acreageText = binding.acreageEditTextView.getText().toString();
                String orientation = orientationAdapter==null ? null : orientationAdapter.getMultipleSelectValue(); //朝向
                String windows; //窗户种类
                if (windowsAdapter==null || windowsAdapter.getSelectValue()==null){
                    windows = null;
                }else {
                    windows = windowsAdapter.getSelectValue().getText();
                }
                cacheSource.setHouseName(houseName);
                if (TextUtils.isEmpty(acreageText)){
                    cacheSource.setAcreage(null);
                }else {
                    cacheSource.setAcreage(acreageText);
                }
                cacheSource.setOrientation(orientation);
                cacheSource.setWindows(windows);
                cacheSource.setViewHouseName(houseCacheName);
                if (cacheAllSources !=null){
                    for (final UploadImageGridViewAdapter.Source s: cacheAllSources) {
                        if (!TextUtils.isEmpty(s.getHouseName()) && s.getHouseName().equals(houseName)
                                && s.getId()!=cacheSource.getId()){
                            String name = houseCacheName==null?houseName:houseCacheName;
                            showDialog(name, () -> finish());
                            return;
                        }
                    }
                }
                break;
        }
        finish();
    }

    @Override
    public void finish() {
        Intent intent = new Intent();
        intent.putExtra("data", cacheSource);
        setResult(RESULT_OK, intent);
        super.finish();
    }



    private boolean check() {
        if (houseNameAdapter != null && (houseNameAdapter.getSelectValue()==null || TextUtils.isEmpty(houseNameAdapter.getSelectValue().getText()))){
            Toast.makeText(this, "请选择房屋名称", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //region 房屋名称展示
    /*
     * @isShow 如果true则显示,false则不显示
     */
    @SuppressWarnings("SameParameterValue")
    private void initHouseNameGridView(boolean isShow, String label, int count){
        String cacheLabel = null;

        if ("卫".equals(label)){
            label = "卫生间";
            cacheLabel ="卫";
        }else if ("厨".equals(label)){
            label = "厨房";
            cacheLabel ="厨";
        }else if ("室内照片".equals(label)){
            cacheLabel = "室内";
        }
        String baseCacheLabel = cacheLabel==null?"":cacheLabel;
        if (isShow){
            binding.houseNameLayout.setVisibility(View.VISIBLE);
        }else {
            binding.houseNameLayout.setVisibility(View.GONE);
            return;
        }
        List<GridSource> sources = new ArrayList<>();
        String labelName;
        for (int i = 0; i < count; i++) {
            GridSource source = new GridSource();
            GridSource tempSource = null;
            if (i==0){
                source.setChecked(defaultChooseFirst);
            }
            if ("室".equals(label)){
                labelName = "卧室";
                if (count>1){
                    char mC = (char) ('A'+i);
                    labelName = labelName + mC;
                    source.setText(labelName);
                    if (count>=2 && i==(count-1)){
                        tempSource = new GridSource();
                        tempSource.setText("书房");
                    }
                }else {
                    source.setText(labelName);
                }

            }else if ("厅".equals(label)){
                labelName = "客厅";
                if (count>1){
                    char mC = (char) ('A' + i);
                    labelName = labelName + mC;
                    if (count>=2 && i==(count-1)){
                        tempSource = new GridSource();
                        tempSource.setText("餐厅");
                    }
                }
                source.setText(labelName);
            }else if ("院".equals(label)){
                if (i==0){
                    source.setText("前院");
                }else if (i==1){
                    source.setText("后院");
                }else if (i==2){
                    labelName = "侧院";
                    source.setText(labelName);
                }else {
                    char mC = (char) ('A'+i);
                    labelName = "侧院"+mC;
                    source.setText(labelName);
                }
            }else {
                labelName = label;
                if (count>1){
                    char mC = (char) ('A'+i);
                    labelName = labelName + mC;
                    if (!TextUtils.isEmpty(baseCacheLabel)){
                        cacheLabel = baseCacheLabel;
                        cacheLabel = cacheLabel + mC;
                    }
                }else {
                    if (!TextUtils.isEmpty(baseCacheLabel)){
                        cacheLabel = baseCacheLabel;
                    }
                }
                source.setText(labelName);
            }
            source.setCacheText(cacheLabel);
            sources.add(source);
            if (tempSource!=null){
                tempSource.setCacheText(cacheLabel);
                sources.add(tempSource);
            }
        }
        if (houseNameAdapter == null){
            houseNameAdapter = new SubdividedGridAdapter(this,sources);
            binding.houseNameGridView.setAdapter(houseNameAdapter);
        }
    }

    private void updateHouseNameGridView(String name){
        if (TextUtils.isEmpty(name))return;
        List<GridSource> sources = houseNameAdapter.getSources();
        for (GridSource s:sources) {
            if (TextUtils.equals(s.getText(),name) || TextUtils.equals(s.getCacheText(),name)){
                s.setChecked(true);
            }else {
                s.setChecked(false);
            }
        }
        houseNameAdapter.notifyDataSetChanged();
    }

    //endregion

    //region 面积
    @SuppressWarnings("SameParameterValue")
    private void initAcreageLayout(boolean isShow){
        if (isShow){
            binding.acreageLayout.setVisibility(View.VISIBLE);
        }else {
            binding.acreageLayout.setVisibility(View.GONE);
        }
    }

    private void updateAcreageLayout(String acreage){
        if (!TextUtils.isEmpty(acreage) && !"null".equalsIgnoreCase(acreage)){
            binding.acreageEditTextView.setText(acreage);
        }
    }
    //endregion

    //region 房屋朝向
    @SuppressWarnings("SameParameterValue")
    private void initOrientationGridView(boolean isShow, List<String> faces){
        if (isShow){
            binding.orientationLayout.setVisibility(View.VISIBLE);
        }else {
            binding.orientationLayout.setVisibility(View.GONE);
            return;
        }
        if (faces==null){
            CustomToast.showToast(this,"没有朝向数据",1500);
            return;
        }
        List<GridSource> sources = new ArrayList<>();
        for (int i = 0; i < faces.size(); i++) {
            GridSource source = new GridSource();
            if (i==0){
                source.setChecked(defaultChooseFirst);
            }else {
                source.setChecked(false);
            }
            source.setText(faces.get(i));
            sources.add(source);
        }
        if (orientationAdapter==null){
            orientationAdapter = new SubdividedGridAdapter(this,sources,true);
            binding.orientationGridView.setAdapter(orientationAdapter);
        }
    }
    private void updateOrientationGridView(String faces){
        if (TextUtils.isEmpty(faces)) return;
        String[] split = faces.split(",");
        if (split.length == 0) return;
        List<GridSource> sources = orientationAdapter.getSources();
        for (GridSource s : sources) {
            s.setChecked(false);
        }

        for (GridSource s : sources) {
            for (String s1 : split) {
                if (TextUtils.equals(s.getText(),s1)) {
                    s.setChecked(true);
                    break;
                }
            }
        }
        orientationAdapter.notifyDataSetChanged();
    }
    //endregion
    private boolean defaultChooseFirst = false; //是否默认选中第一个数据
    //region 窗户种类
    @SuppressWarnings("SameParameterValue")
    private void initWindowsGridView(boolean isShow, List<String> windows){
        if (isShow){
            binding.windowsLayout.setVisibility(View.VISIBLE);
        }else {
            binding.windowsLayout.setVisibility(View.GONE);
            return;
        }
        List<GridSource> sources = new ArrayList<>();
        for (int i = 0; i < windows.size(); i++) {
            GridSource source = new GridSource();
            if (i==0){
                source.setChecked(defaultChooseFirst);
            }else {
                source.setChecked(false);
            }
            source.setText(windows.get(i));
            sources.add(source);
        }
        if (windowsAdapter == null){
            windowsAdapter = new SubdividedGridAdapter(this,sources);
            binding.windowsGridView.setAdapter(windowsAdapter);
        }
    }
    private void updateWindowsGridView(String window){
        List<GridSource> sources = windowsAdapter.getSources();
        for (GridSource s:sources) {
            if (s.getText().equals(window)){
                s.setChecked(true);
            }else {
                s.setChecked(false);
            }
        }
        windowsAdapter.notifyDataSetChanged();
    }
    //endregion

    //region 适配器
    private class SubdividedGridAdapter extends BaseAdapter {
        private final List<GridSource> mSources;
        private final Context mContext;
        private boolean doubleMultipleCheck;
        SubdividedGridAdapter(Context context,List<GridSource> sources){
            this.mContext = context;
            this.mSources = sources;
        }

        SubdividedGridAdapter(Context context,List<GridSource> sources,boolean multipleCheck){
            this.mContext = context;
            this.mSources = sources;
            this.doubleMultipleCheck = true;
        }

        @Override
        public int getCount() {
            return mSources.size();
        }

        @Override
        public GridSource getItem(int position) {
            return mSources.get(position);
        }

        @Override
        public long getItemId(int position) {
            return mSources.get(position).getId();
        }


        private GridSource selectedOne, selectedTwo;
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_prospect_subdivided_gridview, parent, false);
            }
            final GridSource source = mSources.get(position);
            CheckBox checkBox = ViewHolderUtil.get(convertView, R.id.checkBoxView);
            if (source.isChecked()){
                if (selectedOne==null){
                    selectedOne = source;
                }else if (doubleMultipleCheck && selectedTwo==null && source!=selectedOne){
                    selectedTwo = source;
                }
            }
            checkBox.setChecked(source.isChecked()); //展示是否被选中
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public synchronized void onClick(View v) {
                    for (GridSource s:mSources) {
                        if (s == source){
                            if (!s.isChecked()){ //选中
                                if (doubleMultipleCheck){
                                    if (selectedOne==null){
                                        s.setChecked(true);
                                        selectedOne = s;
                                    }else if (selectedTwo==null){
                                        s.setChecked(true);
                                        selectedTwo = s;
                                    }else {
                                        selectedOne.setChecked(false);
                                        selectedOne = selectedTwo;
                                        s.setChecked(true);
                                        selectedTwo = s;
                                    }
                                }else {
                                    if (selectedOne!=null){
                                        selectedOne.setChecked(false);
                                    }
                                    s.setChecked(true);
                                    selectedOne = s;
                                }
                                notifyDataSetChanged();
                                break;
                            }else { //取消选中
                                if (doubleMultipleCheck){
                                    if (selectedOne!=null && selectedTwo!=null){
                                        if (selectedOne!=null && selectedOne == s){
                                            s.setChecked(false);
                                            selectedOne=selectedTwo;
                                            selectedTwo = null;
                                        }else if (selectedTwo!=null && selectedTwo == s){
                                            s.setChecked(false);
                                            selectedTwo = null;
                                        }
                                    }
                                }else {
                                    if (s!=selectedOne){
                                        if (selectedOne!=null){
                                            selectedOne.setChecked(false);
                                        }
                                        s.setChecked(true);
                                        selectedOne = s;
                                    }
                                }
                            }
                            notifyDataSetChanged();
                            break;
                        }
                    }
                }
            });
            if (TextUtils.isEmpty(source.getCacheText())){
                checkBox.setText(source.getText());
            }else {
                checkBox.setText(source.getCacheText());
            }


            return convertView;
        }

        List<GridSource> getSources(){
            return mSources;
        }

        String getMultipleSelectValue(){
            if (!doubleMultipleCheck)throw new IllegalArgumentException("非多选选项禁止调用此项");
            StringBuilder builder = new StringBuilder();
            for (GridSource s:mSources){
                if (s.isChecked()){
                    builder.append(s.getText())
                            .append(',');
                }
            }
            if (builder.length()==0)return null;
            return builder.substring(0, builder.length() - 1);
        }

        GridSource getSelectValue() {
            if (doubleMultipleCheck)throw new IllegalArgumentException("多选选项禁止调用此项");
            GridSource source = null;
            for (GridSource s:mSources) {
                if (s.isChecked()){
                    source = s;
                    break;
                }
            }
            return source;
        }
    }

    /*
     * 表格
     */
    private class GridSource {
        private int id;
        private String cacheText; //缩略内容，当此字段不为null时，列表中优先显示此字段。但是上传的还是text字段
        private boolean checked;
        private String text;

        public String getCacheText() {
            return cacheText;
        }

        public void setCacheText(String cacheText) {
            this.cacheText = cacheText;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public boolean isChecked() {
            return checked;
        }

        public void setChecked(boolean checked) {
            this.checked = checked;
        }

        public void setText(String text) {
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public GridSource clone(){
            GridSource source = new GridSource();
            source.setChecked(checked);
            source.setText(text);
            source.setId(id);
            source.setCacheText(cacheText);
            return source;
        }
    }
    //endregion


    public void finishActivity(){
        this.finish();
    }

    @Override
    protected void onDestroy() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
            binding.scrollView.getViewTreeObserver().removeGlobalOnLayoutListener(innerOnGlobalLayoutListener);
        } else {
            binding.scrollView.getViewTreeObserver().removeOnGlobalLayoutListener(innerOnGlobalLayoutListener);
        }
        super.onDestroy();
        helper.release();
    }
}
